package com.study.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.study.utils.RedisConstants.*;

@Component
@Slf4j
public class CacheUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final ExecutorService CACHE_EXECUTOR = Executors.newFixedThreadPool(10);

    public void set(String key, Object obj, Long time, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(obj), time, unit);
    }

    public void setLogicalExpire(String key, Object obj, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(obj);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        redisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }

    public  <R,ID> R queryShopThrough(String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallBack,
                                      Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        //根据id从Redis获取店铺信息
        String cache = redisTemplate.opsForValue().get(key);
        //如果有直接返回信息
        if (StrUtil.isNotBlank(cache)) {
            return JSONUtil.toBean(cache, type);
        }
        //如果是空对象则直接返回报错信息，目的是为了缓存穿透
        if (cache != null) {
            return null;
        }

        //如果没有则查询数据库
        R r = dbFallBack.apply(id);

        //如果数据库没有店铺信息则返回错误信息
        if (ObjectUtil.isEmpty(r)) {
            //Redis中存入空数据，防止数据穿透
            redisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        //如果数据库有店铺信息则保存到Redis中
        this.set(key,r,time,unit);

        //返回店铺信息到客户端
        return r;
    }

    public <R,ID> R queryWithlogicalExpire(String keyPrefix,ID id,Class<R> type,Function<ID,R> dbFallBack,
                                            Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        //根据id从Redis获取店铺信息
        String cache = redisTemplate.opsForValue().get(key);
        //如果Redis中没有数据直接返回空信息
        if (StrUtil.isBlank(cache)) {
            return null;
        }

        RedisData redisData = JSONUtil.toBean(cache, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();

        //如果没有过期则直接返回数据
        if(expireTime.isAfter(LocalDateTime.now())){
            return r;
        }
        //如果过去了进行数据重建
        String lockKey = LOCK_SHOP_KEY + id;
        boolean lock = tryLock(lockKey);
        if(lock){
            CACHE_EXECUTOR.submit(() -> {
                try {
                    R apply = dbFallBack.apply(id);
                    setLogicalExpire(key,apply,time,unit);
                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }

        //返回店铺信息到客户端
        return r;
    }

    //获取锁
    private boolean tryLock(String lockKey) {
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(lockKey, "1", 10, TimeUnit.SECONDS);
        return ifAbsent;
    }

    //释放锁
    private void unLock(String lockKey) {
        redisTemplate.delete(lockKey);
    }


}
